package com.demo.mqtt.zigbee.handeler.upload;

import com.demo.mqtt.common.utils.HexConvertUtil;
import com.demo.mqtt.common.utils.mongoResouces.MongoUtil;
import com.demo.mqtt.zigbee.entity.po.WaveUpload.WaveUpload;
import com.demo.mqtt.zigbee.entity.po.WaveUpload.WavesUpLoadPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: mqtt
 * @description: 波形数据上传
 * @author: liuYunKai
 * @create: 2021-03-25 11:56
 */
@Slf4j
@Component
public class WavesDataUpload {
    @Autowired
    private MongoTemplate mongoTemplate;

    public boolean annalyze(String topic, String hesStr, String command) {
        if (!"21".equalsIgnoreCase(command)) {
            return false;
        }

        //todo 数据内容暂定32k，用头Str进行拆分
        String[] contextStrArry = hesStr.split(hesStr.substring(0, 18));

        List<WavesUpLoadPO> wavesUpLoadPOList = new ArrayList<>(contextStrArry.length);

        for (String contextStr : contextStrArry) {
            if(StringUtils.isBlank(contextStr)){
                continue;
            }else {
                contextStr = hesStr.substring(0, 18) + contextStr;
            }
            //去掉尾部验证字段
            String str = contextStr.substring(0,contextStr.length() - 4);

            log.info("解析波形报文：{}",str);
            //按字节解析
            WaveUpload waveUpload = new WaveUpload();
            ByteBuffer buffer = ByteBuffer.wrap(HexConvertUtil.hexStrToByteArrs(str));
            buffer.order(ByteOrder.LITTLE_ENDIAN);
            waveUpload.setByteBuffer(buffer, 0);

            WavesUpLoadPO po = new WavesUpLoadPO(waveUpload);

            wavesUpLoadPOList.add(po);
        }
        long count = mongoTemplate.count(
                new Query(
                        Criteria
                                .where("waveType").is(wavesUpLoadPOList.get(0).getWaveType())
                                .and("waveDir").is(wavesUpLoadPOList.get(0).getWaveDir())
                                .and("waveDate").is(wavesUpLoadPOList.get(0).getWaveDate())
                                .and("waveTime").is(wavesUpLoadPOList.get(0).getWaveTime())
//                                .and("deviceId").is(wavesUpLoadPOList.get(0).getDeviceId())
                ), WavesUpLoadPO.class);
        if (count == 0) {
            MongoUtil.saveAll("zigbee_wave_upload", wavesUpLoadPOList);

        } else {
            log.info("重复调用");
        }

        return true;

    }
}
